<?php
/**
 * 产品管理 
 *
 * @copyright   Copyright 2011, Richie
 * @author      Richie <richbossman@163.com>
 * @package     SMS
 * @link        http://www.letphp.com
 * 
 * $Id: ProductAction.class.php 80 2011-04-18 13:34:13Z 442767452@qq.com $
 */
class ProductAction extends SMSAction {

	//添加产品页面
	function _before_add(){
		if(isset($_GET['cat_id']) && !empty($_GET['cat_id'])){
			$detail_content = true;
			$category = D('Category')->getCategory(intval($_GET['cat_id']));
			//分类位置
			$this->assign('position', D('Category')->getCategoryPosition($_GET['cat_id']));
			//品牌
			$this->assign('brands', D('Brand')->brandOptions());
			//仓库
			$this->assign('stores', D('Store')->storeOptions());
			//产品属性
			$this->assign('attributes', (empty($category['attr_group_id'])) ? array() : D('Attribute')->getAttributeGroup($category['attr_group_id']));
			//产品可选规格
			$this->assign('spec', (empty($category['attr_group_id'])) ? array() : D('Attribute')->getAttributeGroup($category['attr_group_id'], 0));
			//print_r(M()->getLastSql());
			//分类信息
			$this->assign('category', $category);	
			//产品默认选中的属性
			$this->assign('selectedAttribute', array());		
		}else{
			$detail_content = false;
			$cat = D('Category');
			$this->assign('cat_list', A('Category')->optionCategory($cat->getAllCategory()));
		}
		$this->assign('detail_content', $detail_content);
	}
	
	//处理添加产品的操作
	function _before_insert(){
		
		//图片
		$_POST['img_url'] = $this->uploadProductFile();
		$model = D('Product');
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		$id = $model->add();
		if($id){
			//处理属性
			$attr = $this->getPostAttribute();
			if($attr){
				foreach ($attr as $attrid){
					M('Pattr')->add(array('product_id'=>$id, 'attr_id'=>$attrid));
				}
			}
			//处理规格
			$spec = $this->getPostAttribute('spec');
			if($spec){
				foreach ($spec as $specid){
					M('Pattr')->add(array('product_id'=>$id, 'attr_id'=>$specid, 'is_spec'=>'1'));
				}
			}
		}else{
			$this->error('产品添加失败，请稍后再试。');
		}
		$this->success('产品添加成功。');
	}
	
	//产品编辑页面
	function _before_edit(){
		$detail_content = true;
		$vo = D('Product')->getById(intval($_GET['id']));
		$category = D('Category')->getCategory($vo['cat_id']);
		//分类位置
		$this->assign('position', D('Category')->getCategoryPosition($vo['cat_id']));
		//品牌
		$this->assign('brands', D('Brand')->brandOptions());
		//仓库
		$this->assign('stores', D('Store')->storeOptions());
		//产品属性
		$this->assign('attributes', (empty($category['attr_group_id'])) ? array() : D('Attribute')->getAttributeGroup($category['attr_group_id']));
		$this->assign('selectedAttribute', D('Pattr')->getProductAllAttribute($vo['id']));
		//产品规格
		$this->assign('spec', (empty($category['attr_group_id'])) ? array() : D('Attribute')->getAttributeGroup($category['attr_group_id'], 0));
		$this->assign('detail_content', $detail_content);
	}
	
	//产品编辑的处理
	function _before_update(){
		$id = intval($_POST['id']);
		if(empty($id)){
			$this->error('产品数据错误！');
		}
		$img_url = $this->uploadProductFile();
		if($img_url) $_POST['img_url'] = $img_url;
		$model = D ( 'Product' );
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		// 更新数据
		$list = $model->save ();
		// 处理产品属性
		if(!empty($_POST['attr'])){
			$oldAttrId = D('Pattr')->getProductAllAttribute($id);
			$attr = $this->getPostAttribute();
			// 添加新的属性
			foreach ($attr as $attrid){
				if(!in_array($attrid, $oldAttrId)){
					D('Pattr')->add(array('product_id'=>$id, 'attr_id'=>$attrid));
				}
			}
			// 删除取消掉的属性
			foreach ($oldAttrId as $oid){
				if(!in_array($oid, $attr)){
					D('Pattr')->where(array('product_id'=>$id, 'attr_id'=>$oid))->delete();
				}
			}
		}
		// 处理产品规格
		if(!empty($_POST['spec'])){
			$oldSpecId = D('Pattr')->getProductAllAttribute($id, true);
			$spec = $this->getPostAttribute('spec');
			// 添加新规格
			foreach ($spec as $specid){
				if(!in_array($specid, $oldSpecId)){
					D('Pattr')->add(array('product_id'=>$id, 'attr_id'=>$specid, 'is_spec'=>1));
				}
			}
			// 删除取消掉的规格
			foreach ($oldSpecId as $specid){
				if(!in_array($specid, $spec)){
					D('Pattr')->where(array('product_id'=>$id, 'attr_id'=>$specid, 'is_spec'=>1))->delete();
				}
			}
		}
	}
	
	//分类选择
	function select_category(){
		echo json_encode(D('Category')->getAllCategoryForTree(0, false));
	}
	
	//产品列表
	function plist(){
		$result = array();
		$where = "";
		$this->datagrid['sort'] = isset($_REQUEST['sort']) ? 'n.'.trim($_REQUEST['sort']) : 'n.sort';
		$result['total'] = M()->table(C('DB_PREFIX').'product AS n')->where($where)->count();
		$result['rows'] = M()->table(C('DB_PREFIX').'product AS n')
				->field('n.id, n.name, n.sn, n.cat_id, n.store_id, n.brand_id, n.stock_number, n.add_time')
				->page($this->datagrid['page'])
				->limit($this->datagrid['rows'])
				->order($this->datagrid['sort'].' '.$this->datagrid['order'])
				->where($where)
				->findAll();
		foreach ($result['rows'] as $key=>$row){
			$result['rows'][$key]['add_time'] = date('Y-m-d H:i', $row['add_time']);
		}
		$result['sql'] = M()->getLastsql();
		$this->ajaxReturn('', $result);
	}
	
	/* 按钮 */
	function _button_product_index(){
		return array('add');
	}
	
	function _button_product_add(){
		return array('index');
	}
	
	function _button_product_edit(){
		return array('index', 'add');
	}
	
	//处理上传的图片
	private function uploadProductFile(){
		$imgurl = '';
		if(isset($_FILES['img_url_file']) && $_FILES['img_url_file']['tmp_name'] && $_FILES['img_url_file']['tmp_name'] != 'none'){
			$upload = new UploadFile('', array('jpg', 'gif', 'png', 'bmp'), array(), '', 'uniqid');
			$upload->upload(UPLOAD_PATH.date('Ymd').'/');
			if($upload_error = $upload->getErrorMsg()){
				$this->error($upload_error);
			}else{
				$file = $upload->getUploadFileInfo();
				$imgurl = str_replace(ROOT_PATH, '', $file[0]['savepath'].$file[0]['savename']);
			}
		}
		return $imgurl;
	}
	
	//取得post的属性，一维数组
	private function getPostAttribute($name='attr'){
		if(empty($_POST[$name])) return array();
		$allattr = array();
		foreach($_POST[$name] as $attr){
			$allattr = array_merge($allattr, $attr);
		}
		return $allattr;
	}
	
	//供库存使用的属性
	private function getPostAttrbiteForStock(){
		if(empty($_POST['attr'])) return array();
		$allattr = array();
		
	}
}
?>